import Vue from 'vue'
import Vuex from 'vuex'

//1.安装插件
Vue.use(Vuex)

//2.创建Store对象
const store = new Vuex.Store({
    state: {
        cartList: []
    },
    mutations: {
        addCounter(state, payload) {
            payload.count++
        },
        addToCart(state, payload) {
            state.cartList.push(payload)
        }
    },
    actions: {
        addCart(context, payload) {
            return new Promise((res) => {
                //1.查找之前数组中是否有该商品
                let oldProduce = context.state.cartList.find(item => item.iid === payload.iid)
                    //2.判断oldProduce
                if (oldProduce) {
                    context.commit('addCounter', oldProduce)
                    res('当前数量+1')
                } else {
                    payload.count = 1
                        // context.state.cartList.push(payload)
                    context.commit('addToCart', payload)
                    res('添加了新的商品')
                }
            })

        }

    }
})

export default store